package com.itheima.health.quartz;

import com.itheima.health.dao.SetMealDao;
import com.itheima.health.service.SetMealService;
import com.itheima.health.util.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
@Slf4j
@Component
public class AliyunOssScanClean {
//    @Scheduled(cron = "*/5 * * * * ?")
//    public  void  run(){
//        System.out.println("----执行扫描一次1---");
//    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private QiniuUtils qiniuUtils;
    @Autowired
    private SetMealService setMealService;
    //删除七牛云中的垃圾图片
    @Scheduled(cron = "0 0 2 * * ?")  //每天2点执行一次
    public void run(){
        log.info("[执行了删除七牛云垃圾图片操作]");
        //获取redis中所有得图片名
        Set img = redisTemplate.boundSetOps("img").members();
        for (Object o : img) {
            String imgName=o.toString();
            //根据图片名查询数据库看是否应用了此图片
            Integer count=setMealService.selectCountByImgName(imgName);
            if(count>0){
                //删除缓存中存放的垃圾图片名
                redisTemplate.boundSetOps("img").remove(imgName);
                continue;
            }
            String creatTime = imgName.substring(0, imgName.indexOf("_"));
            //将字符串转换Long类型
            long creatTime1 = Long.parseLong(creatTime);
            //再获取当前时间
            long endTime = System.currentTimeMillis();  //获取的是毫秒值
            //两者相减
            Long timeMs= endTime-creatTime1;
            if(timeMs>30*60*1000){ //判断图片是否是在1:30-2:00上传
               continue;           //是的话,就不删除-跳出本次循环
            }
            qiniuUtils.deleteFileFromQiniu(imgName);
        }
    }
}
